﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Dapper;
using Weight.Base;
using Weight.Model;

namespace Weight.Dal
{
    public class DalField
    {
        /// <summary>
        /// 获取所有的字段和别名
        /// </summary>
        /// <returns></returns>
        public IEnumerable<FieldEntity>  GetFieldAlias()
        {
            using (IDbConnection conn = SessionFactory.CreateConnection())
            {
                string sql = @" select * from  Alias  where IsShow=@IsShow";
                return conn.Query<FieldEntity>(sql,new { IsShow= true});
            }
        }

        /// <summary>
        ///获取字段通过表名
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public IEnumerable<FieldEntity> GetFieldByTable(string tableName)
        {
            using (IDbConnection conn = SessionFactory.CreateConnection())
            {
                string sql = @" select * from  Alias  where tableName=@tableName order by Rank asc ";
                return  conn.Query<FieldEntity>(sql, new { tableName });
            }
        }

        /// <summary>
        /// 根据表名称查询要展示的字段
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <returns></returns>
        public string GetSqlFieldByTabName(string tableName)
        {
            using (IDbConnection conn = SessionFactory.CreateConnection())
            {
                string sql = @" select * from  Alias  where tableName=@tableName order by Rank asc ";
                IEnumerable< FieldEntity> datas =  conn.Query<FieldEntity>(sql,new { tableName });
                List<string> list = new List<string>();
                string field = string.Empty;
                foreach(var item in datas)
                {
                    if(item.IsShow)
                    {
                        field = "[" + item.Field + "]";
                        if (!list.Contains(field))
                        {
                            list.Add(field);
                        }
                    }
                }

                return string.Join(",",list);
            }
        }

    }
}
